package org.javaforever.infinity.complexverb;

import java.util.ArrayList;
import java.util.List;

import org.javaforever.infinity.core.Writeable;
import org.javaforever.infinity.domain.Domain;
import org.javaforever.infinity.domain.DragonHideStatement;
import org.javaforever.infinity.domain.JavascriptBlock;
import org.javaforever.infinity.domain.JavascriptMethod;
import org.javaforever.infinity.domain.Method;
import org.javaforever.infinity.domain.Signature;
import org.javaforever.infinity.domain.Statement;
import org.javaforever.infinity.domain.StatementList;
import org.javaforever.infinity.domain.Type;
import org.javaforever.infinity.domain.Var;
import org.javaforever.infinity.easyui.EasyUIPositions;
import org.javaforever.infinity.generator.NamedStatementGenerator;
import org.javaforever.infinity.generator.NamedStatementListGenerator;
import org.javaforever.infinity.utils.InterVarUtil;
import org.javaforever.infinity.utils.SqlReflector;
import org.javaforever.infinity.utils.StringUtil;
import org.javaforever.infinity.utils.WriteableUtil;

public class Assign extends TwoDomainVerb implements EasyUIPositions{

	@Override
	public Method generateDaoImplMethod() throws Exception {
		Method method = new Method();
		method.setStandardName("assign"+this.slave.getCapFirstDomainName()+"To"+this.master.getCapFirstDomainName());	
		method.setThrowException(true);
		method.addSignature(new Signature(1,InterVarUtil.DB.connection.getVarName(),InterVarUtil.DB.connection.getVarType()));
		method.addSignature(new Signature(2, StringUtil.lowerFirst(this.master.getStandardName())+"Id", this.master.getDomainId().getClassType()));
		method.addSignature(new Signature(3, StringUtil.lowerFirst(this.slave.getStandardName())+"Id", this.slave.getDomainId().getClassType()));
		method.setReturnType(new Type("Integer"));
		
		List<Writeable> list = new ArrayList<Writeable>();
		list.add(new Statement(100L,2, "String "+InterVarUtil.DB.query.getVarName()+" = \""+SqlReflector.generateInsertLinkTwoSql(master,slave) +"\";"));
		list.add(NamedStatementGenerator.getPrepareStatementWithReturnGeneratedKeys(200L,2, InterVarUtil.DB.ps, InterVarUtil.DB.query, InterVarUtil.DB.connection));
		list.add(new Statement(300L,2,InterVarUtil.DB.ps.getVarName()+"."+this.master.getDomainId().getClassType().getTypeSetterName()+"(1,"+this.master.getLowerFirstDomainName()+"Id);"));
		list.add(new Statement(400L,2,InterVarUtil.DB.ps.getVarName()+"."+this.slave.getDomainId().getClassType().getTypeSetterName()+"(2,"+this.slave.getLowerFirstDomainName()+"Id);"));
		list.add(new Statement(500L,2,"int result = "+InterVarUtil.DB.ps.getVarName()+".executeUpdate();"));
		list.add(new Statement(600L,2,"return result;"));
		method.setMethodStatementList(WriteableUtil.merge(list));
		return method;
	}
	
	@Override
	public String generateDaoImplMethodString() throws Exception {
		Method m = this.generateDaoImplMethod();
		String s = m.generateMethodString();
		return s;
	}

	@Override
	public String generateDaoImplMethodStringWithSerial() throws Exception {
		Method m = this.generateDaoImplMethod();
		m.setContent(m.generateMethodContentStringWithSerial());
		m.setMethodStatementList(null);
		return m.generateMethodString();
	}

	@Override
	public Method generateDaoMethodDefinition() throws Exception {
		Method method = new Method();
		method.setStandardName("assign"+this.slave.getCapFirstDomainName()+"To"+this.master.getCapFirstDomainName());
		method.setReturnType(new Type("Integer"));
		method.setThrowException(true);
		method.addAdditionalImport("java.util.List");
		
		method.addSignature(new Signature(1,InterVarUtil.DB.connection.getVarName(),InterVarUtil.DB.connection.getVarType()));
		method.addSignature(new Signature(2, StringUtil.lowerFirst(this.master.getStandardName())+"Id", this.master.getDomainId().getClassType()));
		method.addSignature(new Signature(3, StringUtil.lowerFirst(this.slave.getStandardName())+"Id", this.slave.getDomainId().getClassType()));
		return method;
	}

	@Override
	public String generateDaoMethodDefinitionString() throws Exception {
		return generateDaoMethodDefinition().generateMethodDefinition();
	}

	@Override
	public Method generateServiceMethodDefinition() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.lowerFirst(getVerbName()));
		method.setReturnType(new Type("Boolean"));
		method.setThrowException(true);
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.master.getStandardName())+"Id", this.master.getDomainId().getClassType()));
		method.addSignature(new Signature(2, StringUtil.lowerFirst(this.slave.getStandardName())+"Ids", new Type("String")));
		return method;
	}

	@Override
	public String generateServiceMethodDefinitionString() throws Exception {
		return generateServiceMethodDefinition().generateMethodDefinition();
	}

	@Override
	public Method generateServiceImplMethod() throws Exception {
		Method method = new Method();
		method.setStandardName(StringUtil.lowerFirst(getVerbName()));
		method.setReturnType(new Type("Boolean"));
		method.setThrowException(true);
		method.addAdditionalImport("java.util.List");
		method.addAdditionalImport(this.master.getPackageToken()+".dao."+this.master.getStandardName()+"Dao");
		method.addAdditionalImport(this.slave.getPackageToken()+".service."+this.slave.getStandardName()+"Service");
		method.addSignature(new Signature(1, StringUtil.lowerFirst(this.master.getStandardName())+"Id", this.master.getDomainId().getClassType()));
		method.addSignature(new Signature(2, StringUtil.lowerFirst(this.slave.getStandardName())+"Ids", new Type("String")));
		method.addMetaData("Override");	
		
		List<Writeable> list = new ArrayList<Writeable>();
		list.add(NamedStatementGenerator.getDBConfInitDBAutoRelease(500L, 2, InterVarUtil.DB.connection, InterVarUtil.DB.dbconf));
		list.add(new Statement(1000L,3,"String [] "+this.slave.getLowerFirstDomainName()+"IdsArr = "+this.slave.getLowerFirstDomainName()+"Ids.split(\",\");"));
		list.add(new Statement(2000L,3,"for (int i = 0; i < "+this.slave.getLowerFirstDomainName()+"IdsArr.length; i++ ){"));
		list.add(new DragonHideStatement(3000L,4,"String "+this.slave.getLowerFirstDomainName()+"Id = "+this.slave.getLowerFirstDomainName()+"IdsArr[i];",this.slave.getDomainId().getClassType().toString().equals("String")));
		list.add(new DragonHideStatement(3000L,4,"Long "+this.slave.getLowerFirstDomainName()+"Id = Long.parseLong("+this.slave.getLowerFirstDomainName()+"IdsArr[i]);",this.slave.getDomainId().getClassType().toString().equals("Long")));
		list.add(new DragonHideStatement(3000L,4,"Integer "+this.slave.getLowerFirstDomainName()+"Id = Integer.parseInt("+this.slave.getLowerFirstDomainName()+"IdsArr[i]);",this.slave.getDomainId().getClassType().toString().equals("Integer")));
		list.add(new Statement(4000L,4,"Integer success = dao."+generateDaoMethodDefinition().generateStandardCallString()+";"));
		list.add(new Statement(5000L,4,"if (success < 0) return false;"));
		list.add(new Statement(6000L,3,"}"));
		list.add(new Statement(7000L,3,"return true;"));
		list.add(new Statement(7500L,2,"}"));
		method.setMethodStatementList(WriteableUtil.merge(list));
		return method;
	}

	@Override
	public String generateServiceImplMethodString() throws Exception {
		return generateServiceMethodDefinition().generateMethodDefinition();
	}

	@Override
	public String generateServiceImplMethodStringWithSerial() throws Exception {
		Method m = this.generateServiceImplMethod();
		m.setContent(m.generateMethodContentStringWithSerial());
		m.setMethodStatementList(null);
		return m.generateMethodString();
	}

	@Override
	public Method generateFacadeMethod() throws Exception {
		Method method = new Method();
		method.setStandardName("processRequest");
		method.setReturnType(new Type("void"));
		method.setThrowException(true);
		List<String> list = new ArrayList<String>();
		list.add("ServletException");
		list.add("IOException");
		method.setIsprotected(true);
		method.setOtherExceptions(list);
		method.addSignature(new Signature(1,"request",new Type("HttpServletRequest","javax.servlet.http")));
		method.addSignature(new Signature(2,"response",new Type("HttpServletResponse","javax.servlet.http")));
		method.addAdditionalImport("java.io.IOException");
		method.addAdditionalImport("java.io.PrintWriter");
		method.addAdditionalImport("javax.servlet.ServletException");
		method.addAdditionalImport("javax.servlet.http.HttpServlet");
		method.addAdditionalImport("javax.servlet.http.HttpServletRequest");
		method.addAdditionalImport("javax.servlet.http.HttpServletResponse");
		method.addAdditionalImport("java.util.Map");
		method.addAdditionalImport("java.util.TreeMap");
		method.addAdditionalImport("net.sf.json.JSONObject");
		method.addAdditionalImport(this.master.getPackageToken()+".utils.StringUtil");
		method.addAdditionalImport(this.master.getPackageToken()+".domain."+this.master.getStandardName());
		method.addAdditionalImport(this.slave.getPackageToken()+".domain."+this.slave.getStandardName());
		method.addAdditionalImport(this.master.getPackageToken()+".service."+this.master.getStandardName()+"Service");
		method.addAdditionalImport(this.master.getPackageToken()+".serviceimpl."+this.master.getStandardName()+"ServiceImpl");
		
		List<Writeable> wlist = new ArrayList<Writeable>();
		Var service = new Var("service", new Type(this.master.getStandardName()+"Service",this.master.getPackageToken()));
		Var resultMap = new Var("result", new Type("TreeMap<String,Object>","java.util"));
		wlist.add(NamedStatementGenerator.getFacadeSetContentType(1000L, 2, InterVarUtil.Servlet.response, InterVarUtil.SimpleJEE.UTF8.getVarName()));
		wlist.add(NamedStatementGenerator.getControllerPrintWriterOut(2000L, 2, InterVarUtil.Servlet.response, InterVarUtil.Servlet.out));
		wlist.add(NamedStatementGenerator.getJsonResultMap(3000L, 2, resultMap));
		wlist.add(new Statement(4000L,2, service.getVarType() +" " +service.getVarName() +" = new " +service.getVarType()+"Impl();"));
		wlist.add(NamedStatementGenerator.getTryHead(5000L, 2));
		wlist.add(new Statement(6000L,3,this.master.getDomainId().getFieldType()+ " " + this.master.getLowerFirstDomainName()+"Id = "+Type.getInitTypeWithVal(this.master.getDomainId().getClassType())+";"));
		wlist.add(new Statement(7000L,3,"String " + this.slave.getLowerFirstDomainName()+"Ids = \"\";"));
		wlist.add(new DragonHideStatement(8000L,3,"if (!StringUtil.isBlank(request.getParameter(\""+this.master.getLowerFirstDomainName()+"Id\"))) "+this.master.getLowerFirstDomainName()+"Id = Long.parseLong(request.getParameter(\""+this.master.getLowerFirstDomainName()+"Id\"));",this.master.getDomainId().getFieldType().equalsIgnoreCase("long")));
		wlist.add(new DragonHideStatement(8000L,3,"if (!StringUtil.isBlank(request.getParameter(\""+this.master.getLowerFirstDomainName()+"Id\"))) "+this.master.getLowerFirstDomainName()+"Id = Integer.parseInt(request.getParameter(\""+this.master.getLowerFirstDomainName()+"Id\"));",this.master.getDomainId().getFieldType().equals("int")||this.master.getDomainId().getFieldType().equals("Integer")));
		wlist.add(new Statement(9000L,3,"if (!StringUtil.isBlank(request.getParameter(\""+this.slave.getLowerFirstDomainName()+"Ids\"))) "+this.slave.getLowerFirstDomainName()+"Ids = request.getParameter(\""+this.slave.getLowerFirstDomainName()+"Ids\");"));
		wlist.add(new Statement(10000L,3,"boolean success = "+service.getVarName()+"."+this.generateServiceMethodDefinition().getStandardCallString()+";"));
		wlist.add(new Statement(11000L,3, resultMap.getVarName()+".put(\"success\",success);"));
		wlist.add(new Statement(12000L,3, resultMap.getVarName()+".put(\"data\",null);"));
		wlist.add(NamedStatementGenerator.getEncodeMapToJsonResultMap(13000L, 3, resultMap,InterVarUtil.Servlet.out));
		wlist.add(NamedStatementListGenerator.generateCatchExceptionPrintStackPrintJsonMapFinallyCloseOutFooter(14000L, 2, InterVarUtil.Servlet.response, resultMap, InterVarUtil.Servlet.out));
		method.setMethodStatementList(WriteableUtil.merge(wlist));		
		return method;
	}

	@Override
	public String generateFacadeMethodString() throws Exception {
		Method m = this.generateFacadeMethod();
		return m.generateMethodString();
	}

	@Override
	public String generateFacadeMethodStringWithSerial() throws Exception {
		Method m = this.generateFacadeMethod();
		m.setContent(m.generateMethodContentStringWithSerial());
		m.setMethodStatementList(null);
		return m.generateMethodString();
	}
		
	public Assign(Domain master,Domain slave){
		super();
		this.master = master;
		this.slave = slave;
		this.setVerbName("Assign"+this.slave.getCapFirstPlural()+"To"+this.master.getCapFirstDomainName());
		this.setLabel("分配");
	}


	@Override
	public JavascriptBlock generateEasyUIJSButtonBlock() throws Exception {
		return null;
	}

	@Override
	public String generateEasyUIJSButtonBlockString() throws Exception {
		return null;
	}

	@Override
	public String generateEasyUIJSButtonBlockStringWithSerial() throws Exception {
		return null;
	}

	@Override
	public JavascriptMethod generateEasyUIJSActionMethod() throws Exception {
		JavascriptMethod method = new JavascriptMethod();
		method.setSerial(200);
		method.setStandardName(StringUtil.lowerFirst(this.getVerbName()));
		
		StatementList sl = new StatementList();
		sl.add(new Statement(1000,1, "var "+this.slave.getLowerFirstDomainName()+"Ids = new Array();"));
		sl.add(new Statement(2000,1, "var rows = $(\"#myAvailable"+this.slave.getCapFirstPlural()+"\").datalist(\"getSelections\");"));
		sl.add(new Statement(3000,1, "if (isBlank(rows)) {"));
		sl.add(new Statement(4000,1, "$.messager.alert(\"操作提示\", \"请选择可添加"+this.slave.getText()+"！\");"));
		sl.add(new Statement(5000,1, "return;"));
		sl.add(new Statement(6000,1, "}"));
		sl.add(new Statement(7000,1, "for (var i = 0;i<rows.length;i++){"));
		sl.add(new Statement(8000,1, this.slave.getLowerFirstDomainName()+"Ids[i] = rows[i][\""+this.slave.getDomainId().getLowerFirstFieldName()+"\"]; "));
		sl.add(new Statement(9000,1, "}"));
		sl.add(new Statement(10000,1, "var "+this.master.getLowerFirstDomainName()+"Id = $(\"#my"+this.master.getCapFirstDomainName()+"\").datalist(\"getSelected\")."+this.master.getDomainId().getLowerFirstFieldName()+";"));
		sl.add(new Statement(11000,1, "$.ajax({"));
		sl.add(new Statement(12000,1, "type: \"post\","));
		sl.add(new Statement(13000,1, "url: \"../facade/"+StringUtil.lowerFirst(this.getVerbName())+"Facade\","));
		sl.add(new Statement(14000,1, "data: {"));
		sl.add(new Statement(15000,1, this.slave.getLowerFirstDomainName()+"Ids:"+this.slave.getLowerFirstDomainName()+"Ids.join(\",\"),"));
		sl.add(new Statement(16000,1, this.master.getLowerFirstDomainName()+"Id:"+this.master.getLowerFirstDomainName()+"Id,"));
		sl.add(new Statement(17000,1, "},"));
		sl.add(new Statement(18000,1, "dataType: 'json',"));
		sl.add(new Statement(19000,1, "success: function(data, textStatus) {"));
		sl.add(new Statement(20000,1, "if (data.success) $(\"#my"+this.master.getCapFirstDomainName()+"\").datalist(\"load\");"));
		sl.add(new Statement(21000,1, "},"));
		sl.add(new Statement(22000,1, "complete : function(XMLHttpRequest, textStatus) {"));
		sl.add(new Statement(23000,1, "},"));
		sl.add(new Statement(24000,1, "error : function(XMLHttpRequest,textStatus,errorThrown) {"));
		sl.add(new Statement(25000,1, "alert(\"Error:\"+textStatus);"));
		sl.add(new Statement(26000,1, "alert(errorThrown.toString());"));
		sl.add(new Statement(27000,1, "}"));
		sl.add(new Statement(28000,1, "});"));
		
		method.setMethodStatementList(sl);
		return method;	
	}

	@Override
	public String generateEasyUIJSActionString() throws Exception {
		return generateEasyUIJSActionMethod().generateMethodString();
	}

	@Override
	public String generateEasyUIJSActionStringWithSerial() throws Exception {
		return generateEasyUIJSActionMethod().generateMethodStringWithSerial();
	}	
}
